//============================================================================
// Name        : cpp_math.cpp
// Author      : darkflash
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <math.h>
#include <stdlib.h>
#include <ctime>
using namespace std;

void fnPrintMode(){
	cout << "1. Round" << endl;
	cout << "2. Random" << endl;
	cout << "q. quit" << endl;
}

int getch(void)
{
	int ch;
	struct termios oldt;
	struct termios newt;
	tcgetattr(STDIN_FILENO, &oldt); /*store old settings */
	newt = oldt; /* copy old settings to new settings */
	newt.c_lflag &= ~(ICANON | ECHO); /* make one change to old settings in new settings */
	tcsetattr(STDIN_FILENO, TCSANOW, &newt); /*apply the new settings immediatly */
	ch = getchar(); /* standard getchar call */
	tcsetattr(STDIN_FILENO, TCSANOW, &oldt); /*reapply the old settings */
	return ch; /*return received char */
}

double fnRound(double num, int pos){
	double rtn;

	rtn = num * pow(10, pos);
	rtn = floor(rtn + 0.5);
	rtn *= pow(10, -pos);

	return rtn;
}

void fnRoundMode(){
	string input_num, input_pos;

	cout << "input num: ";
	cin >> input_num;
	getchar();

	cout << "input pos: ";
	cin >> input_pos;
	getchar();

	double round = fnRound(atof(input_num.c_str()), atoi(input_pos.c_str()));
	cout << round << endl;
}

int fnRandom(int min, int max){
	int rtn;

	srand((unsigned int)time(NULL));
	rtn = rand()%max + min;

	return rtn;
}

void fnRandomMode(){
	string input_min, input_max;

	cout << "input min: ";
	cin >> input_min;
	getchar();

	cout << "input max: ";
	cin >> input_max;
	getchar();

	int random = fnRandom(atoi(input_min.c_str()), atoi(input_max.c_str()));
	cout << random << endl;;
}

int main() {
	int input_mode;

	do{

		fnPrintMode();
		input_mode = getch();

		switch(input_mode){
		case '1':
			fnRoundMode();
			break;
		case '2':
			fnRandomMode();
			break;
		}

	}while(input_mode != 'q');

	return 0;
}
